package com.oeandn.system.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.oeandn.common.model.PageModel;
import com.oeandn.system.model.ScheduleInfo;
import com.oeandn.system.mapper.ScheduleInfoMapper;
import com.oeandn.db.base.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;

/**
 * <p>
 * 排班 服务实现类
 * </p>
 *
 * @author 饮水机管理员
 * @since 2022-08-10
 */
@Service
public class ScheduleInfoService extends BaseService<ScheduleInfoMapper, ScheduleInfo> {

    /**
     * 获取表格数据
     *
     * @param scheduleInfo
     * @return
     */
    public List<ScheduleInfo> list(ScheduleInfo scheduleInfo) {
        LambdaQueryWrapper<ScheduleInfo> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.likeLeft(StrUtil.isNotBlank(scheduleInfo.getYearMonth()), ScheduleInfo::getScheduleDate, scheduleInfo.getYearMonth());
        queryWrapper.orderByAsc(ScheduleInfo::getScheduleDate);
        List<ScheduleInfo> list = super.list(queryWrapper);
        if(!list.isEmpty()){
            ScheduleInfo info = list.get(0);
            if(info.getWeekCode() != 7) {
                int id = info.getId().intValue() - (7 - info.getWeekCode());
                LambdaQueryWrapper<ScheduleInfo> first = Wrappers.lambdaQuery();
                first.gt(ScheduleInfo::getId, id);
                first.lt(ScheduleInfo::getId,info.getId());
                first.orderByDesc(ScheduleInfo::getScheduleDate);
                List<ScheduleInfo> firstList = super.list(first);
                list.addAll(firstList);
            }

            ScheduleInfo lastInfo = list.get(list.size() - 1);
            if(lastInfo.getWeekCode() != 6){
                int id = lastInfo.getId().intValue() + (7 - info.getWeekCode());
                LambdaQueryWrapper<ScheduleInfo> first = Wrappers.lambdaQuery();
                first.le(ScheduleInfo::getId, id);
                first.gt(ScheduleInfo::getId,info.getId());
                first.orderByAsc(ScheduleInfo::getScheduleDate);
                List<ScheduleInfo> firstList = super.list(first);
                list.addAll(firstList);
            }
        }
        //根据id排序
        list.sort(Comparator.comparing(ScheduleInfo::getId));
        return list;
    }

}
